package com.example.androidthreadtest

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.widget.Button
import android.widget.ImageView
import android.widget.TextView
import androidx.work.OneTimeWorkRequest
import androidx.work.WorkManager
import com.example.androidthreadtest.extensions.loadImageFromNet
import kotlin.concurrent.thread

class MainActivity : AppCompatActivity() {

    private val txt1 = 1
    private val txt2 = 2
    private var lastTxt = 0

    private val handler = object : Handler(Looper.getMainLooper()) {
        override fun handleMessage(msg: Message) {
            val textView = findViewById<TextView>(R.id.textView)
            // 在这里可以进行UI操作
            when (msg.what) {
                txt1 -> textView.text = "Nice to meet you"
                txt2 -> textView.text = "很高兴认识你"
            }
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val changeTextBtn = findViewById<Button>(R.id.changeTextBtn)
        changeTextBtn.setOnClickListener {
            thread {
                val msg = Message()
                msg.what = if (lastTxt == txt1) txt2 else txt1
                lastTxt = msg.what
                handler.sendMessage(msg) // 将Message对象发送出去
            }
        }

        val doWorkBtn : Button = findViewById(R.id.doWorkBtn)
        doWorkBtn.setOnClickListener(){
            val imageView = findViewById<ImageView>(R.id.imageView)
            val imageUrl = "http://172.25.44.120:9433/texture/mango_big.jpg"
            imageView.loadImageFromNet(this, imageUrl)
        }
    }

}